package com.buss.core.persistence;

import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import com.buss.core.utils.StringUtil;


public class OrderBy implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -5451918343188085904L;

	public static final String ASC = "asc";

	public static final String DESC = "desc";

	private Map<String, String> order = new LinkedHashMap<String, String>();

    private String sidx = "id";

    private String sord = DESC;

    /**
     * @return the sidx
     */
    public String getSidx() {
        return sidx;
    }

    /**
     * @param sidx the sidx to set
     */
    public void setSidx(String sidx) {
        this.sidx = sidx;
        this.add(sidx, getSord());
    }

    /**
     * @return the sord
     */
    public String getSord() {
        return sord;
    }

    /**
     * @param sord the sord to set
     */
    public void setSord(String sord) {
        this.sord = sord;
        if(StringUtil.isNotEmpty(getSidx())){
            if(order.get(getSidx()) != null){
                order.remove(getSidx());
                this.add(sidx, sord);
            }
        }
    }

	/**
	 * 添加排序字段和排序方式
	 * @param key
	 * @param value
	 */
	public void add(String key,String value){
		if(StringUtil.isNotEmpty(key)){
			if (StringUtil.isEmpty(value) && !value.equals(ASC) && !value.equals(DESC)) value = "asc";
			order.put(key, value);
		}
	}

	/**
	 * 删除排序字段
	 * @param key
	 */
	public void remove(String key){
		if(StringUtil.isNotEmpty(key)){
			order.remove(key);
		}
	}

	/**
	 * 获取排序方式
	 * @param key
	 * @return
	 */
	public String getValue(String key){
		return order.get(key);
	}

	/**
	 * 合并排序字段
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String aggOrder(String param){
                if(StringUtil.isEmpty(param)){
                    return "";
                }
		String sql = " order by ";
		int i = 1;
		if(StringUtil.isNotEmpty(param)){
			param += ".";
		}
		if(order.size() == 0){
			sql += param +"id " + ASC;			
		}
		Iterator iter = order.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry<String, String> entry = (Map.Entry<String, String>)iter.next();
			if(i < order.size()){
				sql += param + entry.getKey() + " " + entry.getValue() + ",";
			}else{
				sql += param + entry.getKey() + " " + entry.getValue();
			}
			i++;
		}
		return sql;
	}

	public static void main(String[] args){
		OrderBy order = new OrderBy();
		order.add("id", DESC);
		order.add("time", ASC);
		System.out.println(order.aggOrder("a"));
	}
}
